package com.cardbaobao.cardbabyclient.ui.fragment.findbank;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.callback.OnLocationListener;
import com.cardbaobao.cardbabyclient.model.BankNet;
import com.cardbaobao.cardbabyclient.model.LatLng;
import com.cardbaobao.cardbabyclient.model.MyLocation;
import com.cardbaobao.cardbabyclient.ui.activity.CitySelectActivity;
import com.cardbaobao.cardbabyclient.ui.activity.FindBankActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.base.CommonAdapter;
import com.cardbaobao.cardbabyclient.ui.adapter.base.ViewHolder;
import com.cardbaobao.cardbabyclient.ui.dialog.NavDialog;
import com.cardbaobao.cardbabyclient.ui.fragment.base.BaseFragment;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.LocationUtil;
import com.cardbaobao.cardbabyclient.utils.NavUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.pulltorefresh.XListView;

import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * 找银行和网点搜索共用
 * Created by zad
 * 2017/1/10 14:01
 */

public class BankNetFragment extends BaseFragment {
    private String prePageId;
    public void setBuriedInfo(String prePageId){
        this.prePageId=prePageId;
    }
    /**
     * 网点列表
     */
    @BindView(R.id.id_lv_net)
    XListView mLvNetPos;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;

    private String bankName = "";

    @Override
    protected int getLayoutId() {
        return R.layout.layout_fragment_netpos;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    protected void initViewFinish(View view, Bundle savedInstanceState) {
        mLvNetPos.setPullRefreshEnable(false);
        mLvNetPos.setPullLoadEnable(false);

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        startLocation();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CitySelectActivity.REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                String cityName = data.getStringExtra(CitySelectActivity.RESULT_CITY_NAME_KEY);
                loadData(cityName, null, null);
            } else {
                showList(false);
            }
        }
    }

    /**
     * 开启定位获取当前经纬度
     */
    private void startLocation() {
        LocationUtil.startLocation(mContext, new OnLocationListener() {
            @Override
            public void locationResult(MyLocation location, int resultCode) {
                if (location == null) {
                    ToastUtil.showToastLongOnScreenCenter("定位失败，请选择您当前所在城市");
                    Intent intent = new Intent(getContext(), CitySelectActivity.class);
                    startActivityForResult(intent, CitySelectActivity.REQUEST_CODE);
                } else {
                    String keyWord;
                    if (!TextUtils.isEmpty(bankName)) {
                        keyWord = bankName;
                    } else {
                        keyWord = location.getCityName();
                    }
                    LatLng latLng = location.getLatLng();
                    loadData(keyWord,
                            String.valueOf(latLng.getLongitude()),
                            String.valueOf(latLng.getLatitude()));
                }
            }
        });
    }

    private void loadData(String cityName, String longitude, String latitude) {
        showProgressDialog(false);
        Observable<String> observable = Api.nearbyBankOutlets("0", cityName, longitude, latitude);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                dismissProgressDialog();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                List<BankNet> data = JsonUtil.getDataLists(s, BankNet.class);
                if (data != null && data.size() > 0) {
                    showList(true);
                    mLvNetPos.setAdapter(new CommonAdapter<BankNet>(mContext, data, R.layout.item_bank_net) {
                        @Override
                        public void convert(ViewHolder holder, final BankNet item, int position) {
                            hideDivider((LinearLayout) holder.getConvertView());//隐藏顶部间隔
                            holder.displayImage(R.id.id_iv_bank_logo,
                                    URLUtil.CBB_IMG_URL + item.getBankLogo(),
                                    R.drawable.icon_index_money);//网点logo
                            if (!TextUtils.isEmpty(item.getBankwdName())) {
                                holder.setText(R.id.id_tv_bank_title, item.getBankName() + "-" + item.getBankwdName());//银行名称
                            } else {
                                holder.setText(R.id.id_tv_bank_title, item.getBankName());//银行名称
                            }
                            holder.setText(R.id.id_tv_bank_address, item.getAddress());//地址
                            holder.setText(R.id.id_tv_distance, item.getDistance() + "米");//距离
                            //导航单击事件
                            holder.getView(R.id.ll_nav).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //导航单击事件
                                    SelfUtils.buriedClickData(Self.Action.app_click_near_by_bank_net_point_item,
                                            Self.Action.app_click_near_by_bank_net_point_item_des,
                                            mEnterPageTime,
                                            mCurrentPageId,
                                            prePageId);
                                    showNavDialog(item);
                                }
                            });
                        }
                    });
                } else {
                    showList(false);
                }
            }
        });
    }

    private void showList(boolean showList) {
        if (showList) {
            mLvNetPos.setVisibility(View.VISIBLE);
            llNoData.setVisibility(View.GONE);
        } else {
            mLvNetPos.setVisibility(View.GONE);
            llNoData.setVisibility(View.VISIBLE);
        }
    }

    private NavDialog mNavDialog;

    private void showNavDialog(final BankNet item) {
        if (mNavDialog == null) {
            mNavDialog = new NavDialog(mContext);
        }
        mNavDialog.setOnNavMenuListener(new NavDialog.OnNavMenuListener() {
            @Override
            public void onBaiDuNavClick(View v) {
                //百度导航
                NavUtil.toBaiDuNav(mContext, item);
            }

            @Override
            public void onAutoNavClick(View v) {
                //高德导航
                NavUtil.toAutoNav(mContext, item);
            }
        });
        mNavDialog.show();
    }

    public void setBankName(String bankName) {
        this.bankName = bankName;
    }
}
